package com.dhms.uikit.deviceCategory

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.dhms.uikit.databinding.ItemDeviceCategoryBinding

class DeviceCategoryListAdapter(private val onItemClick: (categoryItem: DeviceCategoryItem) -> Unit = {}) :
    ListAdapter<DeviceCategoryItem, DeviceCategoryListAdapter.DeviceCategoryListViewHolder>(
        DiffCallback
    ) {

    class DeviceCategoryListViewHolder(var binding: ItemDeviceCategoryBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(item: DeviceCategoryItem) {
            binding.item = item
            binding.executePendingBindings()
        }
    }

    companion object DiffCallback : DiffUtil.ItemCallback<DeviceCategoryItem>() {

        override fun areItemsTheSame(
            oldItem: DeviceCategoryItem,
            newItem: DeviceCategoryItem
        ): Boolean {
            return oldItem == newItem
        }

        override fun areContentsTheSame(
            oldItem: DeviceCategoryItem,
            newItem: DeviceCategoryItem
        ): Boolean {
            return oldItem == newItem
        }
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): DeviceCategoryListViewHolder {
        return DeviceCategoryListViewHolder(
            ItemDeviceCategoryBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        )
    }

    override fun onBindViewHolder(holder: DeviceCategoryListViewHolder, position: Int) {
        val item = getItem(position)
        holder.bind(item)
        holder.binding.chipItem.setOnClickListener {
            onItemClick.let { it1 -> it1(item) }
        }
    }

}